package de.hsb.ai.devil.ui;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.Border;

import de.hsb.ai.devil.agent.InteractivePlayerAgent;
import de.hsb.ai.devil.util.Result;


public class DevilGui extends JFrame {
	
	private InteractivePlayerAgent agent;
	
	private Result<Integer> result;
	
	private JLabel remainderLabel;
	
	private class ResultActionHandler implements ActionListener {
		private int delta;
		public ResultActionHandler(int delta) {
			this.delta = delta;
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			if (result != null) {
				synchronized (result) {
					result.set(delta);
					result.notifyAll();
				}
			}
		}
	}
	
	public DevilGui(InteractivePlayerAgent humanAgent) {
		super("Human Devil Player");
		setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		agent = humanAgent;
		setup();
		pack();
	}
	
	public void getDelta(Result<Integer> result, int total) {
		this.result = result;
		this.remainderLabel.setText("Remainder: " + total);
		this.setVisible(true);
		this.requestFocus();
	}
	
	private void setup() {
		JPanel infoPanel = new JPanel();
		Border infoPanelBorder = BorderFactory.createTitledBorder("Info");
		infoPanel.setBorder(infoPanelBorder);
		
		remainderLabel = new JLabel("N/A");
		infoPanel.add(remainderLabel);
		
		JPanel btnPanel = new JPanel();
		btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.LINE_AXIS));
		
		JButton btn1 = new JButton("Take 1");
		JButton btn2 = new JButton("Take 2");
		JButton btn3 = new JButton("Take 3");
		
		btn1.addActionListener(new ResultActionHandler(1));
		
		btn2.addActionListener(new ResultActionHandler(2));
		
		btn3.addActionListener(new ResultActionHandler(3));
		
		btnPanel.add(btn1);
		btnPanel.add(btn2);
		btnPanel.add(btn3);
		
		JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
		mainPanel.add(infoPanel, BorderLayout.NORTH);
		mainPanel.add(btnPanel, BorderLayout.CENTER);
		add(mainPanel);
	}

	public void handleGameOver(boolean win) {
		JOptionPane.showMessageDialog(this, "You " + (win ? "won" : "lost"));
		setVisible(false);
		remainderLabel.setText("N/A");
	}
	
}
